#!/usr/bin/python3

import os
import json
import time


def check_indox():
    return "secret data from indox"


def is_login():
    # 从环境变量中获取所有cookie的值
    cookies = os.getenv('HTTP_COOKIE', '')
    cookies = dict([x.strip().split('=') for x in cookies.split(';')])
    sid = cookies.get('sessionid')
    if sid:
        # 找到session数据对应的文件，
        # 打开文件，读取内容，用json解析内容，生成字典
        session_file = os.path.join(session_dir, sid)
        try:
            session_data = json.loads(open(session_file).read())
        except FileNotFoundError:
            return False

        # 如果session里面找不到expire（不应该出现这种情况），就当它过期
        expire = session_data.get('expire', 0)
        now = int(time.time())
        if expire > now:
            return True

    return False


expire = 86400
session_dir = '/tmp/.session_data'


if __name__ == '__main__':
    if is_login():
        text = check_indox()
    else:
        text = """
<html>
<head>
</head>
<body>
<p style="color: red">login required</p>
<a href="/login.html">Log in</a>
</body>
</html>
"""
    print('Content-Type: text/html\n\n', end='')
    print(text)
